//
//  HeroViewController.m
//  LOL_JewelBox
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "HeroViewController.h"
#import "HeroModel.h"
#import "HeroView.h"
#import "AFNetworking.h"
#import "DetailHeroViewController.h"
#import "DOPDropDownMenu.h"
#import "HeroCollectionCell.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "GMDCircleLoader.h"
@interface HeroViewController ()<DOPDropDownMenuDataSource,DOPDropDownMenuDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>

@property(nonatomic, retain)NSMutableArray *allHeroArr;
@property(nonatomic, retain)NSMutableArray *freeHeroArr;
@property(nonatomic, retain)UICollectionView *heroCollectionView;
@property(nonatomic, retain)NSArray *allHero;
@property(nonatomic, retain)NSArray *freeHero;
@property(nonatomic, retain)NSArray *sort;
@property(nonatomic, retain)NSMutableArray *transformArr;
@property(nonatomic, retain)UISearchBar *heroSearch;
@property(nonatomic,retain)UIView *hiddenView;
@property(nonatomic,retain)UITableView *searchTableView;
@property(nonatomic, retain)NSMutableArray *searchArr;
@end

@implementation HeroViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.allHeroArr = [NSMutableArray array];
        self.freeHeroArr = [NSMutableArray array];
        self.transformArr = [NSMutableArray array];
        self.searchArr  = [NSMutableArray array];

    }
    self.title = @"英雄界面";
        return self;
}
// 内存释放
- (void)dealloc
{
    [_allHero release];
    [_freeHero release];
    [_sort release];
    [_freeHeroArr release];
    [_allHeroArr release];
    [_hiddenView release];
    [_searchArr release];
    [_searchTableView release];
    [_heroCollectionView release];
    [_transformArr release];
    [_heroSearch release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self createHeroView];
    [self heroData];


    // Do any additional setup after loading the view.
    // 创建自定义视图





}
// 创建视图

- (void)createHeroView
{
    HeroView *heroView = [[HeroView alloc] initWithFrame:CGRectMake(0, 0, VIEWWIDTH, VIEWHEIGHT)];
    heroView.backgroundColor = [UIColor whiteColor];
    heroView.tag = 10000;
    [self.view addSubview:heroView];
    [heroView release];

    // 创建英雄UIcollectionView

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(VIEWWIDTH * 0.226666, VIEWHEIGHT * 0.1649175);
    flowLayout.minimumInteritemSpacing = VIEWWIDTH * 0.013333333;
    flowLayout.minimumLineSpacing = VIEWWIDTH * 0.013333333;
    flowLayout.headerReferenceSize = CGSizeMake(VIEWWIDTH, VIEWHEIGHT * 0.104947);
    flowLayout.sectionInset = UIEdgeInsetsMake(VIEWWIDTH * 0.013333333, VIEWWIDTH * 0.013333333, VIEWWIDTH * 0.013333333, VIEWWIDTH * 0.013333333);
    self.heroCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, VIEWWIDTH, VIEWHEIGHT - VIEWHEIGHT * 0.1799100449) collectionViewLayout:flowLayout];
    [heroView addSubview:self.heroCollectionView];
    self.heroCollectionView.backgroundColor = [UIColor whiteColor];
    [_heroCollectionView release];
    self.heroCollectionView.dataSource = self;
    self.heroCollectionView.delegate = self;

    [self.heroCollectionView registerClass:[HeroCollectionCell class] forCellWithReuseIdentifier:@"reuse"];



    // 筛选条件框
    self.freeHero = @[@"欢乐一周"];
    self.allHero = @[@"召唤师峡谷"];
    self.sort = @[@"筛选",@"刺客",@"坦克",@"法师",@"战士",@"射手",@"辅助"];

    // 添加下拉菜单

    DOPDropDownMenu *menu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake(0, VIEWHEIGHT * 0.0449775) andHeight:VIEWHEIGHT * 0.06596701];
    menu.dataSource = self;
    menu.delegate = self;
    menu.tag = 2001;
    [heroView addSubview:menu];
    [menu release];	

    // 搜索框
    self.heroSearch = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, VIEWWIDTH, VIEWHEIGHT * 0.0449775112)];
    [heroView addSubview:self.heroSearch];
    [_heroSearch release];
    self.heroSearch.placeholder = @"请输入英雄名称";
    self.heroSearch.delegate = self;
    self.heroSearch.searchResultsButtonSelected = NO;



    self.hiddenView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEWWIDTH, VIEWHEIGHT)];
    self.hiddenView.backgroundColor = [UIColor clearColor];
    self.hiddenView.alpha = 0.1f;
    self.heroSearch.inputAccessoryView = self.hiddenView;
    [self createSearchTableView];

}
#pragma mark 英雄搜索所有内容
// 为heroSearch建立展示的tableView
- (void)createSearchTableView
{
    self.searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, VIEWHEIGHT * 0.065967016, VIEWWIDTH, 0.76 * VIEWHEIGHT)];
    HeroView *view = (HeroView *)[self.view viewWithTag:10000];
    [view addSubview:self.searchTableView];
    [_searchTableView release];
    self.searchTableView.dataSource = self;
    self.searchTableView.delegate = self;
    self.searchTableView.hidden = YES;
    self.searchTableView.rowHeight = VIEWHEIGHT * 0.144404;
//    self.searchTableView.tableHeaderView = self.heroSearch;



}
// 遮挡视图点击事件 搜索框失去第一响应者
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{   self.heroSearch.showsCancelButton = NO;
    [self.heroSearch resignFirstResponder];
    self.searchTableView.hidden = YES;
    self.heroSearch.text = @"";
    HeroView *heroView = (HeroView *)[self.view viewWithTag:10000];
    DOPDropDownMenu *menu = (DOPDropDownMenu *)[heroView viewWithTag:2001];
    menu.hidden = NO;

}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
     self.heroSearch.showsCancelButton = YES;
    self.searchTableView.hidden = NO;
    HeroView *heroView = (HeroView *)[self.view viewWithTag:10000];
    DOPDropDownMenu *menu = (DOPDropDownMenu *)[heroView viewWithTag:2001];
    menu.hidden = YES;
}


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    HeroView *heroView = (HeroView *)[self.view viewWithTag:10000];
    DOPDropDownMenu *menu = (DOPDropDownMenu *)[heroView viewWithTag:2001];
    menu.hidden = YES;
    [self.searchArr removeAllObjects];
    [self searchHeroData];
    [self.searchTableView reloadData];

}
 - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{    self.heroSearch.text = @"";
     [self.heroSearch resignFirstResponder];
     self.heroSearch.showsCancelButton = NO;
     self.searchTableView.hidden = YES;
    HeroView *heroView = (HeroView *)[self.view viewWithTag:10000];
    DOPDropDownMenu *menu = (DOPDropDownMenu *)[heroView viewWithTag:2001];
    menu.hidden = NO;
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if (self.searchArr.count == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"没有符合搜索条件的英雄,请核对重新输入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    self.heroSearch.keyboardAppearance = UIKeyboardAppearanceAlert;
    [self.heroSearch resignFirstResponder];


}
// 根据输入的数据搜索英雄
- (void)searchHeroData
{   NSString *temp = [self.heroSearch.text capitalizedString];
    if (![temp isEqualToString:@""]) {
        for (HeroModel *hero in self.allHeroArr) {
            if ([hero.enName hasPrefix:temp] || [hero.cnName hasPrefix:temp] || [hero.title hasPrefix:temp]) {
                [self.searchArr addObject:hero];
            }
        }
    }


}

// 搜索tableView必须实现的两个方法
- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    if (self.searchArr.count != 0) {
        self.hiddenView.alpha = 0.0f;
    }
    return self.searchArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *search = @"search";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:search];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:search] autorelease];
    }
    HeroModel *hero = self.searchArr[indexPath.row];
    cell.textLabel.text = hero.cnName;
    NSString *heroImage = [NSString stringWithFormat:@"http://img.lolbox.duowan.com/champions/%@_120x120.jpg",hero.enName];
    NSURL *url = [NSURL URLWithString:heroImage];
    [cell.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"占位图"]];

    return cell;

}

// 搜索到的英雄点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    DetailHeroViewController *detail = [[DetailHeroViewController alloc] init];
    HeroModel *hero = self.searchArr[indexPath.row];
    detail.enName = hero.enName;
    detail.cnName = hero.cnName;
    detail.title1  = hero.title;
    detail.location = hero.location;
    detail.price = hero.price;
    detail.rating = hero.rating;
    [self.navigationController pushViewController:detail animated:YES];
    self.hiddenView.alpha = 0.1f;
    [detail release];
}
#pragma mark CollectionView 代理方法

- (NSInteger )collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{


    return self.transformArr.count;

}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HeroCollectionCell *heroCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    HeroModel *hero = self.transformArr[indexPath.row];
    heroCell.heroTitleLabel.text = hero.title;
    heroCell.heroTitleLabel.font = [UIFont systemFontOfSize:11];
    heroCell.heroTitleLabel.textAlignment = NSTextAlignmentCenter;
    heroCell.heroNameLabel.text = hero.cnName;
    heroCell.heroNameLabel.font = [UIFont systemFontOfSize:12];
    heroCell.heroNameLabel.textAlignment = NSTextAlignmentCenter;


    NSString *heroImage = [NSString stringWithFormat:@"http://img.lolbox.duowan.com/champions/%@_120x120.jpg",hero.enName];
    NSURL *url = [NSURL URLWithString:heroImage];
    [heroCell.heroIronImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"占位图"]];
   

    return heroCell;


}

// collectionView 点击事件

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

    DetailHeroViewController *detail = [[DetailHeroViewController alloc] init];
     HeroModel *hero = self.transformArr[indexPath.row];
    detail.enName = hero.enName;
    detail.cnName = hero.cnName;
    detail.title1  = hero.title;
    detail.location = hero.location;
    detail.price = hero.price;
    detail.rating = hero.rating;
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];


}

#pragma mark 自定义菜单
// 下拉菜单横排组成个数

- (NSInteger )numberOfColumnsInMenu:(DOPDropDownMenu *)menu
{

    return 3;

}

// 子菜单个数
- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column
{
    if (column == 0) {
        return self.freeHero.count;
    }else if (column == 1){
        return self.allHero.count;
    }else {
        return self.sort.count;
    }
}

// 子菜单是否含有子项目 无返回0
- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfItemsInRow:(NSInteger)row column:(NSInteger)column
{
       return 0;
}
// 子项目标题
- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath
{
    if (indexPath.column == 0) {
        return self.freeHero[indexPath.row];
    } else if (indexPath.column == 1){
        return self.allHero[indexPath.row];
    } else {
        return self.sort[indexPath.row];
    }
}


// 子菜单是否含有子项目名称 无返回nil
- (NSString *)menu:(DOPDropDownMenu *)menu titleForItemsInRowAtIndexPath:(DOPIndexPath *)indexPath
{
        return nil;
}

// 点击事件

- (void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath
{      [self.transformArr removeAllObjects];
    if (indexPath.column == 0) {

        // 周免
        for (HeroModel *hero in self.freeHeroArr) {

            [self.transformArr addObject:hero];
            [self.heroCollectionView reloadData];
        }
    }
    else if (indexPath.column == 1)
    {

       // 全部英雄

        for (HeroModel *hero in self.allHeroArr) {

            [self.transformArr addObject:hero];
            [self.heroCollectionView reloadData];

        }
    }
    else if (indexPath.column == 2){
        NSInteger num = indexPath.row;
        switch (num) {
            case 0:
                    // 默认全部英雄
                for (HeroModel *hero in self.allHeroArr) {

                    [self.transformArr addObject:hero];

                    
                }


                break;
                case 1:  // 刺客
                self.transformArr =   [self selectMethod:self.allHeroArr condition:@"assassin"];
                break;

                case 2: // 坦克
                self.transformArr =   [self selectMethod:self.allHeroArr condition:@"tank"];
                   break;

               case 3: // 法师
               self.transformArr =   [self selectMethod:self.allHeroArr condition:@"mage"];
                break;

                case 4: // 战士
                self.transformArr =   [self selectMethod:self.allHeroArr condition:@"fighter"];
                break;

                case 5: // 射手
                self.transformArr =   [self selectMethod:self.allHeroArr condition:@"marksman"];
                break;

                case 6: // 辅助
                self.transformArr =   [self selectMethod:self.allHeroArr condition:@"support"];
                break;

            default:
                break;
        }

              [self.heroCollectionView reloadData];
}



}






#pragma mark 英雄数据解析
// 英雄数据解析
- (void)heroData
{
    [GMDCircleLoader setOnView:self.view withTitle:@"英雄数据加载中..." animated:YES];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://lolbox.duowan.com/phone/apiHeroes.php" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSMutableDictionary *HeroDic = responseObject;
         NSMutableArray *tempArr = HeroDic[@"all"];
         NSMutableArray *tempArr2 = HeroDic[@"free"];

         for (NSMutableDictionary *dic in tempArr) {
             HeroModel *hero = [[HeroModel alloc] init];
             [hero setValuesForKeysWithDictionary:dic];
             [self.allHeroArr addObject:hero];
             [hero release];
         }

         for (NSMutableDictionary *dic in tempArr2) {
             HeroModel *hero = [[HeroModel alloc] init];
             [hero setValuesForKeysWithDictionary:dic];
             [self.freeHeroArr addObject:hero];
             [hero release];
         }

         for (HeroModel *hero in self.freeHeroArr) {

             [self.transformArr addObject:hero];
             [self.heroCollectionView reloadData];
         }


         [GMDCircleLoader hideFromView:self.view animated:YES];

         [self.heroCollectionView reloadData];



     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"网络请求有误");
     }];

    
}

 #pragma mark 英雄筛选条件

- (NSMutableArray *)selectMethod:(NSMutableArray *)array condition:(NSString *)condition
{
    NSMutableArray *tempArr = [NSMutableArray array];
    for (HeroModel *hero in array) {
        if ([hero.tags isEqualToString:condition]) {
            [tempArr addObject:hero];
        }
    }

    return tempArr;
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
